package cn.edu.zjicm.wordsnet_d.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

public class ThirdLoginActivity extends Activity implements OnItemClickListener {
	private GridView gridView = null;
	private TextView nickName;
	private ImageView headImg;
	
	private int[] imgs = {R.drawable.icon_qq_selector,R.drawable.icon_sina_selector,R.drawable.icon_weixin_selector};
	private String[] texts = {"QQ","新浪","微信"};
	private int index = -1;   //点击的序号
	private String nickname;  //昵称
	
	// QQ
	private Tencent mTencent;
	private UserInfo mUserInfo;
	private QQAuth mQqAuth;
	private static final String SCOPE = "get_user_info,get_simple_userinfo,get_user_profile,get_app_friends,"
			+ "add_share,add_topic,list_album,upload_pic,add_album,set_user_face,get_vip_info,get_vip_rich_info,get_intimate_friends_weibo,match_nick_tips_weibo";
	private static final int QQ_FLAG = 0;
	

	// sina
	private WeiboAuth mWeiboAuth;
	private Oauth2AccessToken mAccessToken;
	private IWeiboShareAPI mWeiboShareAPI;
	private SsoHandler mSsoHandler;
	private static final int sina_FLAG = 1;
	private String access_token;
	
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {			
			switch (msg.what) {
			case 0:
				JSONObject object = (JSONObject)msg.obj;
				if(object.has("nickname")){
					try {
						nickname = object.getString("nickname");
						System.out.println("qq名:"+nickname);
						nickName.setText(nickname);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				break;

			case 1:
				Bitmap bitmap = (Bitmap) msg.obj;
				headImg.setImageBitmap(bitmap);
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_third_login);
		gridView = (GridView) findViewById(R.id.third_login_gridView);
		nickName = (TextView) findViewById(R.id.third_login_nickname);
		headImg = (ImageView) findViewById(R.id.third_login_headImg);
		setDatas();
		gridView.setOnItemClickListener(this);
	}

	private void setDatas() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		for (int i = 0; i < texts.length; i++) {
			map = new HashMap<String, Object>();
			map.put("text", texts[i]);
			map.put("img", imgs[i]);
			list.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(ThirdLoginActivity.this, list,
				R.layout.view_third_login_item, new String[] { "img", "text" }, new int[] {
						R.id.third_login_item_img, R.id.third_login_item_text });
		gridView.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		index = position;
		switch (imgs[position]) {
		case R.drawable.icon_qq_selector:
			qqLogin();
			break;
		case R.drawable.icon_sina_selector:
			sinaLogin();
			break;
		case R.drawable.icon_weixin_selector:
			weixinLogin();
			break;

		default:
			break;
		}
	}

	private void weixinLogin() {
		// TODO Auto-generated method stub
		
	}

	private void sinaLogin() {
		// TODO Auto-generated method stub
		mAccessToken = readAccessToken(this);
		if(mAccessToken.isSessionValid()){
			//可以在这里得到token信息
			access_token = mAccessToken.getToken();
		}else{			
			mWeiboAuth = new WeiboAuth(this,StaticData.APP_KEY_SINA_WEIBO, StaticData.REDIRECT_URL,StaticData.SCOPE);
			mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,StaticData.APP_KEY_SINA_WEIBO);
			
			// 判断用户手机是否安装微博客户端
			if (mWeiboShareAPI.isWeiboAppInstalled()) {
				mSsoHandler = new SsoHandler(ThirdLoginActivity.this, mWeiboAuth);
				mSsoHandler.authorize(new AuthListener());
			} else if(!mWeiboShareAPI.isWeiboAppInstalled()){
				mWeiboAuth.anthorize(new AuthListener());
			}
		}
	}

	private void qqLogin() {
		// TODO Auto-generated method stub
		mTencent = Tencent.createInstance(StaticData.APP_ID_QQ,ThirdLoginActivity.this);
		mQqAuth = QQAuth.createInstance(StaticData.APP_ID_QQ,ThirdLoginActivity.this.getApplicationContext());
		if (!mQqAuth.isSessionValid()) {
			IUiListener listener = new BaseIUiListener(){
				@Override
				public void onComplete(Object arg0) {
					// TODO Auto-generated method stub
					updateUserInfo();
				}

				
			};
			//mQqAuth.login(ThirdLoginActivity.this, "all", listener);
			mTencent.loginWithOEM(this, "all", listener, "10000144", "10000144", "xxxx");

		}

	}
	private void updateUserInfo() {
		// TODO Auto-generated method stub
		if(mQqAuth!=null&&mQqAuth.isSessionValid()){
			IUiListener listener = new IUiListener() {
				
				@Override
				public void onError(UiError arg0) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onComplete(final Object arg0) {
					// TODO Auto-generated method stub
					Message msg = new Message();
					msg.obj = arg0;
					msg.what = 0;
					handler.sendMessage(msg);
					new Thread(){
						public void run() {
							JSONObject jsonObject = (JSONObject) arg0;
							if(jsonObject.has("figureurl")){
								Bitmap bitmap = null;
								try {
									bitmap = getbitmap(jsonObject.getString("figureurl_qq_2"));
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								Message msg2 = new Message();
								msg2.obj = bitmap;
								msg2.what = 1;
								handler.sendMessage(msg2);
							}
						};
					}.start();
				}
				
				@Override
				public void onCancel() {
					// TODO Auto-generated method stub
					
				}
			};
			mUserInfo = new UserInfo(ThirdLoginActivity.this,mQqAuth.getQQToken());
			mUserInfo.getUserInfo(listener);
		}
	}
	private class BaseIUiListener implements IUiListener {

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onComplete(Object arg0) {
			// TODO Auto-generated method stub
			doComplete((JSONObject)arg0);
		}
		protected void doComplete(JSONObject values){
			
		}
		@Override
		public void onError(UiError arg0) {
			// TODO Auto-generated method stub

		}

	}
	/**
	 * 根据一个网络连接(String)获取bitmap图像
	 * 
	 * @param imageUri
	 * @return
	 * @throws MalformedURLException
	 */
	public static Bitmap getbitmap(String imageUri) {
		Log.v("Tag", "getbitmap:" + imageUri);
		// 显示网络上的图片
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();

			Log.v("Tag", "image download finished." + imageUri);
		} catch (IOException e) {
			e.printStackTrace();
			Log.v("Tag", "getbitmap bmp fail---");
			return null;
		}
		return bitmap;
	}

	/**
	 * 微博认证授权回调类。 1.SSO 授权时(有客户端时)，需要在 {@link #onActivityResult} 中调用
	 * {@link SsoHandler#authorizeCallBack} 后，该回调才会被执行。 2. 非 SSO
	 * 授权时，当授权结束后，该回调就会被执行。 当授权成功后，请保存该 access_token、expires_in、uid 等信息到
	 * SharedPreferences 中。
	 * 
	 * @author cnting
	 * 
	 */
	private class AuthListener implements WeiboAuthListener {

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			Toast.makeText(ThirdLoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onComplete(Bundle arg0) {
			// TODO Auto-generated method stub
			mAccessToken = Oauth2AccessToken.parseAccessToken(arg0);
			if (mAccessToken!=null&&mAccessToken.isSessionValid()) {
				writeAccessToken(ThirdLoginActivity.this,mAccessToken);
				access_token = mAccessToken.getToken();
				Toast.makeText(ThirdLoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
			}else{
				String msg = "授权失败";
				String code = arg0.getString("code");
				if(!TextUtils.isEmpty(code)){
					msg = msg+"    code:"+code;
				}
				Toast.makeText(ThirdLoginActivity.this, msg, Toast.LENGTH_SHORT).show();
			}
		}



		@Override
		public void onWeiboException(WeiboException arg0) {
			// TODO Auto-generated method stub
			Toast.makeText(ThirdLoginActivity.this, "Auth exception : " + arg0.getMessage(), Toast.LENGTH_LONG).show();
		}

	}
	/*
	 * 写入到SharedPreference，到时候提取出来
	 */
	private void writeAccessToken(Context context,Oauth2AccessToken mAccessToken) {
		// TODO Auto-generated method stub
		if (null == context || null == mAccessToken) {
            return;
        }
		AppPreference.setSinaAccessToken(context, mAccessToken.getToken());
		AppPreference.setSinaUid(context, mAccessToken.getUid());
		AppPreference.setSinaExpiresIn(context, mAccessToken.getExpiresTime());
	}
	
	private Oauth2AccessToken readAccessToken(Context context){
		if(null==context)
			return null;
		Oauth2AccessToken token = new Oauth2AccessToken();
        token.setToken(AppPreference.getSinaAccessToken(context));
        token.setUid(AppPreference.getSinaUid(context));
        token.setExpiresTime(AppPreference.getSinaExpiresIn(context));
        return token;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (index) {
		case QQ_FLAG:
			if (mTencent != null) {
				mTencent.onActivityResult(requestCode, resultCode, data);
			}
			break;

		case sina_FLAG:
			if ((mWeiboShareAPI.isWeiboAppInstalled()) && (mSsoHandler != null)) {
				mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
			}
			break;
		}		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
}
